<?php

namespace App\Models;

use App\Common\Traits\HasAttachments;
use App\Common\Traits\HasAttributes;
use App\Common\Traits\HasValues;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Spatie\Activitylog\Traits\LogsActivity;

/**
 * 商品活动
 */
class CommodityActivity extends Base
{
    use HasAttributes, HasValues, HasAttachments, SoftDeletes, LogsActivity;

    /**
     * 偏远地区运费: 开启
     */
    const REMOTE_REGIONS_FREIGHT_OPEN = 1;

    /**
     * 偏远地区运费: 关闭
     */
    const REMOTE_REGIONS_FREIGHT_CLOSE = 2;

    /**
     * 偏远地区加价方式: 按件
     */
    const BILLING_METHOD_BY_PIECE = 1;

    /**
     * 偏远地区加价方式: 按订单
     */
    const BILLING_METHOD_BY_ORDER = 2;

    /**
     * 上架状态
     */
    const STATUS_PUT_ON_SHELF = 1;

    /**
     * 下架状态
     */
    const STATUS_OFF_SHELF = 2;

    /**
     * 已结束,仅仅占位用,数据库里不存在该值,逻辑上 过了结束时间 就是已结束
     */
    const STATUS_OVER = 3;

    const STATUS_MAP = [
        self::STATUS_PUT_ON_SHELF => '上架',
        self::STATUS_OFF_SHELF => '下架',
        self::STATUS_OVER => '已结束',
    ];

    /**
     * 是否锁定: 激活
     */
    const LOCKING_ACTIVATION = 1;

    /**
     * 是否锁定: 锁定
     */
    const LOCKING_LOCKING = 2;

    const LOCKING_MAP = [
        self::LOCKING_ACTIVATION => '激活',
        self::LOCKING_LOCKING => '锁定',
    ];

    /**
     * 附件类型: 商品主图
     */
    const ATTACHMENT_TYPE_MAIN_PIC = 1;

    /**
     * 附件类型: 商品详情图片
     */
    const ATTACHMENT_TYPE_DETAIL_PIC = 2;

    /**
     * 类型: 今日直播
     */
    const TYPE_LIVE_TODAY = 1;

    /**
     * 类型: 好评返团
     */
    const TYPE_PRAISE_BACK_TO_THE_GROUP = 2;

    /**
     * 类型编号首字母 map
     */
    const TYPE_NUMBERING_PREFIX_MAP = [
        self::TYPE_LIVE_TODAY => 'Z',
        self::TYPE_PRAISE_BACK_TO_THE_GROUP => 'F'
    ];

    /**
     * 推送类型: 不推送
     */
    const PUSH_SETTING_DO_NOT = 1;

    /**
     * 推送类型: 立即推送
     */
    const PUSH_SETTING_NOW = 2;

    /**
     * 推送类型: 定时推送
     */
    const PUSH_SETTING_REGULARLY = 3;

    /**
     * 推送类型: 每日推送
     */
    const PUSH_SETTING_DAILY = 4;

    /**
     * 活动类型对应的订单类型
     */
    const TYPE_WITH_ORDER_TYPE = [
        self::TYPE_LIVE_TODAY => 'ZB',
        self::TYPE_PRAISE_BACK_TO_THE_GROUP => 'HP'
    ];

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
        'remote_regions_freight_setting' => 'array',
    ];

    protected static function boot()
    {
        static::addGlobalScope('orderBySortIdDesc', function (Builder $builder) {
            $builder->orderBy('sort_id', 'ASC');
        });

        parent::boot(); // Base 的创建时间排序在后面, 优先 sort_id 排序
    }

    /**
     * 活动拥有的标签
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function labels()
    {
        return $this->belongsToMany(CommodityLabel::class, 'commodity_activity_label', 'activity_id', 'label_id');
    }

    /**
     * 活动所属的商品
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function commodity()
    {
        return $this->belongsTo(Commodity::class);
    }

    /**
     * 活动拥有的 sku
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function skus()
    {
        return $this->hasMany(CommodityActivitySku::class);
    }

    /**
     * 只查询 上架状态 作用域
     * @param $query
     * @return mixed
     */
    public function scopePutOnShelf($query)
    {
        return $query->where('commodity_activities.status', self::STATUS_PUT_ON_SHELF);
    }

    /**
     * 在抢购时间范围内
     * @param $query
     * @return mixed
     */
    public function scopePanicBuyingTime($query, \DateTime $date = null)
    {
        $date === null && $date = Carbon::now();

        return $query
            ->where('commodity_activities.panic_buying_start_time', '<=', $date)
            ->where('commodity_activities.panic_buying_end_time', '>=', $date);
    }

    /**
     * 素材
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function materials()
    {
        return $this->hasMany(CommodityActivityPushMaterial::class);
    }

    /**
     * 朋友圈素材
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function moments()
    {
        return $this->hasMany(CommodityActivityMomentsMaterial::class);
    }

    /**
     * 统计
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function statistics()
    {
        return $this->hasOne(CommodityActivityStatistics::class);
    }

    /**
     * 购买限制
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function purchaseRestriction()
    {
        return $this->hasMany(CommodityActivityPurchaseRestriction::class);
    }

    /**
     * 自定义操作日志 说明
     * @param $eventName
     * @return string
     */
    public function getDescriptionForEvent(string $eventName): string
    {
        if (in_array($eventName, ['deleted', 'updated'])) {
            switch ($eventName) {
                case 'deleted':
                    return sprintf('删除商品活动: %s (%s)', $this['name'] ?? '', $this['numbering'] ?? '');
                case 'updated':
                    if (!$this->wasChanged()) {
                        return '';
                    }

                    if (Arr::has($this->getChanges(), 'locking')) {
                        activity()
                            ->on($this)
                            ->by(\Auth::user())
                            ->withProperty('ip', app('request')->ip())
                            ->log(sprintf(self::LOCKING_MAP[$this->getAttribute('locking')] . '商品活动: %s (%s)', $this['name'] ?? '', $this['numbering'] ?? ''));
                    }

                    if (Arr::has($this->getChanges(), 'status')) {
                        activity()
                            ->on($this)
                            ->by(\Auth::user())
                            ->withProperty('ip', app('request')->ip())
                            ->log(sprintf(self::STATUS_MAP[$this->getAttribute('status')] . '商品活动: %s (%s)', $this['name'] ?? '', $this['numbering'] ?? ''));
                    }


//                    $changesMap = ['name' => '类别名称', 'sort_id' => '排序'];
//                    $changes = [];
//                    foreach (Arr::only($this->getChanges(), ['name', 'sort_id']) as $field => $value) {
//                        $changes[] = [
//                            'field' => $changesMap[$field],
//                            'text' => $this->getOriginal($field) . ' 改为 ' . $value
//                        ];
//                    }
//
//                    return sprintf('编辑商品活动: %s', array_reduce($changes, fn ($init, $item) => $init . ($item['field'] . ' ' . $item['text']) . '; ', ''));
            }
        }

        return '';
    }
}
